﻿using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

using Microsoft.Extensions.Hosting;

namespace Jack.RedisEventBus.WebApiDemo.EventBus
{
    public class AutoGenerateOrderEventHostedService : BackgroundService
    {
        private readonly IEventPublisher _eventPublisher;

        public AutoGenerateOrderEventHostedService(IEventPublisher eventPublisher)
        {
            _eventPublisher = eventPublisher;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (stoppingToken.IsCancellationRequested == false)
            {
                try
                {
                    await RunAsync(stoppingToken);
                    await Task.Delay(5000, stoppingToken);
                }
                catch (Exception)
                {
                }
            }
        }

        private async Task RunAsync(CancellationToken stoppingToken)
        {
            int eventCount = 10;
            List<OrderEvent> orderEvents = new List<OrderEvent>();
            for (int i = 0; i < eventCount; i++)
            {
                orderEvents.Add(new OrderEvent { OrderNo = Guid.NewGuid().ToString() });
            }
            await _eventPublisher.Publish(orderEvents);
        }
    }
}
